import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Drawer, Flex, Form, Select, Input, message } from "antd";
import { apiSysDictSelect } from '../../../../services/common';
import { apiMSDTagAdd, apiMSDTagEdit, apiMSDTagView } from '../../../../services/masterData/tag';
import { SYSCODE, CONFIG_ITEM_KEYS } from '../../../../utils/constant';
import { getUserName, transformArray } from '../../../../utils/commonUtil';

const EditModal = ({
  openDrawer,
  setOpenDrawer,
  editSucessFn,
  editType,
  recordData,
}) => {
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const { TextArea } = Input;
  const [buList, setBuList] = useState([]);
  const [moduleList, setModuleList] = useState([]);
  const [typeList, setTypeList] = useState([]);
  const [initialData, setInitialData] = useState();
  const { MD_TAG_TYPE, BU, MODULE } = CONFIG_ITEM_KEYS;

  const apiMSDTagSaveSync = async (params) => {
    const { data } = editType === 'edit' ? await apiMSDTagEdit(params) : await apiMSDTagAdd(params);
    if (data?.code === 200) {
      message.success(t('common.saveSuccess'));
      setOpenDrawer(false);
      editSucessFn();
    }
  };
  const saveClickHandle = () => {
    const params = form?.getFieldsValue();
    params.userId = getUserName();
    params.tag = params?.tag?.trim();
    params.standardTag = params?.standardTag?.trim();
    if (editType === 'edit') {
      params.tagTemplateId = recordData.tagTemplateId;
    };
    // params.tagGroup = params?.tagGroup?.join(';');
    form.validateFields().then(() => {
      apiMSDTagSaveSync(params);
    }, () => {
      return false;
    });
  };
  const initModalData = async () => {
    const params = {
      sysCode: SYSCODE,
      dictCodes: [MD_TAG_TYPE, BU, MODULE]
    };
    const { data } = await apiSysDictSelect(params);
    setTypeList(transformArray(data?.data?.[MD_TAG_TYPE]));
    setBuList(transformArray(data?.data?.[BU]));
    setModuleList(transformArray(data?.data?.[MODULE]));

    let initData = {};
    if (editType === 'new') {
      // initData.tagGroup = data?.data?.[BU];
    } else {
      const resData = await apiMSDTagView({ id: recordData.tagTemplateId });
      const detialData = resData?.data?.data?.item;
      // detialData.tagGroup = detialData?.tagGroup?.split(';');
      initData = detialData
    };
    setInitialData(initData);
  };

  useEffect(() => {
    initModalData();
  }, []);

  return (
    <>
      {
        initialData &&
        <Drawer
          title={t(`common.${editType}`)}
          footer={
            <Flex justify='flex-end'>
              <Button type="primary" onClick={saveClickHandle} disabled={editType === 'view'}>{t('common.save')}</Button>
            </Flex>
          }
          placement="right"
          onClose={() => setOpenDrawer(false)}
          open={openDrawer}
          width={600}>
          <Form form={form} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }} initialValues={initialData} disabled={editType === 'view'}>
            <Form.Item name="buType" label={t('common.bu')}
              rules={[
                {
                  required: true,
                  message: t('common.selectRequired'),
                }
              ]}>
              <Select placeholder={t('common.pleaseSelect')} allowClear options={buList} />
            </Form.Item>
            <Form.Item name="moduleName" label={t('common.module')}
              rules={[
                {
                  required: true,
                  message: t('common.selectRequired'),
                }
              ]}>
              <Select placeholder={t('common.pleaseSelect')} allowClear options={moduleList} />
            </Form.Item>
            <Form.Item name="tagType" label={t('common.type')}
              rules={[
                {
                  required: true,
                  message: t('common.selectRequired'),
                }
              ]}>
              <Select placeholder={t('common.pleaseSelect')} allowClear options={typeList} />
            </Form.Item>
            <Form.Item name="tag" label={t('common.tagName')}
              rules={[
                {
                  required: true,
                  message: t('common.inputRequired'),
                }
              ]}>
              <Input placeholder={t('common.pleaseEnter')} disabled={editType !== 'new'} />
            </Form.Item>
            <Form.Item name="standardTag" label={t('masterData.standardTagName')}>
              <Input placeholder={t('common.pleaseEnter')} />
            </Form.Item>
            <Form.Item name="remark" label={t('common.remarks')}>
              <TextArea placeholder={t('common.pleaseEnter')} />
            </Form.Item>
          </Form>
        </Drawer>
      }
    </>
  )
};

export default EditModal;